package net.satiri.panaroekan;

import java.util.Timer;
import java.util.TimerTask;

import net.satiri.panaroekan.config.PanaroekanConfig;
import net.satiri.panaroekan.datasource.JsonRequest;
import net.satiri.panaroekan.listener.PanaroekanLocationListener;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class panaroekan extends Activity {
	
	public static final String PREFS_NAME = "panaroekan_preferences";
	
	private PanaroekanConfig cf  = null;
	private String logtag = "";
	private Timer myTimer;
	
	//form object
	private EditText txtLong = null;
	private EditText txtLat = null;
	private EditText txtTags = null;
	private EditText txtKeterangan = null;
	private Button btnSend = null;
	private Button btnGet = null;
	
	private Context ctx;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.panaroekan_menu, menu);
	    return true;
	}
	
	private void openConfig(){
		Intent i = new Intent(this, net.satiri.panaroekan.activity.PanaroekanConfig.class);
		startActivity(i);
	}
	
	private void initForm(){
		
		txtLong = (EditText)findViewById(R.id.TxtLongitude);
		txtLat = (EditText)findViewById(R.id.TxtLatitude);
		txtTags = (EditText)findViewById(R.id.TxtTags);
		txtKeterangan = (EditText)findViewById(R.id.TxtKeterangan);
		
		btnSend = (Button)findViewById(R.id.ButtonRequest);
		btnGet = (Button)findViewById(R.id.ButtonUpdate);
	}
	
	private void resetForm(){
		txtLong.setText("");
		txtLat.setText("");
		txtTags.setText("");
		txtKeterangan.setText("");
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.PanaroekanMnuConfig:
	            openConfig();
	            return true;
	        case R.id.PanaroekanMnuTrace:
	            //showHelp();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
		 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        SharedPreferences settings = getPreferences(MODE_APPEND);
        LoadPreferences();
        
        ctx = getApplicationContext();
    	LocationManager mlocManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
    	LocationListener mlocListener = new PanaroekanLocationListener(ctx);
    	mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
        
        cf = new PanaroekanConfig();
        logtag = cf.getLogtag();
        setContentView(R.layout.main);
    
        
        myTimer = new Timer();
		myTimer.schedule(new TimerTask() {			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				getGpsValue();
			}
		},(long)5*1000,(long)5*1000);
			
        
        initForm();
        setBinding();
        
    }
            
    private void getGpsValue(){
    	Log.i(this.logtag,"update gps value");
    }
    
    
    private void setBinding()
    {
    	
    	//update position
    	btnGet.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				ProgressDialog dialog = ProgressDialog.show(panaroekan.this, "", 
                        "Loading. Please wait...", true);
				try{
					String lastLat = ((PanaroekanApp)ctx.getApplicationContext()).getLastLat();
					String lastLong = ((PanaroekanApp)ctx.getApplicationContext()).getLastLong();
					
					txtLong.setText(lastLong);
					txtLat.setText(lastLat);
					
				}catch(Exception e)
				{
					
				}
				dialog.dismiss();
			}
		});
    	
    	//bind send button	
        btnSend.setOnClickListener(new View.OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				ProgressDialog dialog = ProgressDialog.show(panaroekan.this, "", 
                        "Loading. Please wait...", true);
				int result = runRequest();
				Log.i(panaroekan.this.logtag,"status : " + result);
				if(result==0){
					dialog.dismiss();
					Toast.makeText(panaroekan.this, "Sending Sukses", 2000);
					resetForm();
				}else{
					dialog.dismiss();
					//show alert
					Toast.makeText(panaroekan.this, "Sending Gagal", 2000);
				}
			}
		});    	
        
        
    }
    
    private String getValue(EditText text){
    	return text.getText().toString();
    }
    
    
    //contoh baca shared preferences
    private void LoadPreferences(){
    	try{
        SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
        String panaroekan_server = sharedPreferences.getString("panaroekan_server", "");
        String panaroekan_pin = sharedPreferences.getString("panaroekan_pin", "");
        String panaroekan_timer = sharedPreferences.getString("panaroekan_timer", "");
    	}catch(Exception e){
    		
    	}
     }
    
    private int runRequest()
    {
    	
        JSONObject ja = new JSONObject();
        try{
        	ja.put("lon", getValue(txtLong));
        	ja.put("lat", getValue(txtLat));
        	ja.put("tags", getValue(txtTags));
        	ja.put("keterangan", txtKeterangan.getText().toString());
        	
        	Log.i(this.logtag,"Sukses mengisi json");
        	
        }catch(Exception e){
        	Log.e(this.logtag,"Gagal mengisi json");
        	
        }
        
        String url = cf.getUrlcek();
        JSONObject jArray = JsonRequest.getJSONfromURL(url,"record",ja.toString());
        if(jArray!=null){
        	try{
        		Log.i(this.logtag,"Jarray Sukses " + Integer.parseInt(jArray.getString("status")));
        		Log.i(this.logtag,"Jarray Sukses " + jArray.getString("lon"));
        		Log.i(this.logtag,"Jarray Sukses " + jArray.getString("record"));
        		
        		return 0;
        	}catch(Exception e){
        		Log.i(this.logtag,"Send Sukses ");        	
        		
        		return 1;
        	}
        }else{
        	Log.e(this.logtag,"Jarray is null");
        	return 1;
        }     
    }
}